package com.fjwt.gz.pay.mch.mchstar;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.pay.PayKit;
import com.fjwt.gz.zhyx.AESUtils;
import com.fjwt.gz.zhyx.SignUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class MchStarService {
    /**
     * 获取商户星级
     **/
    public List<MchStar> getMchStar(JSONObject jsonObject) {
        log.info("获取商户星级未加密请求参数：{}", JSONUtil.toJsonStr(jsonObject));
        String mchStarUrl = PayKit.MCH_STAR_URL;
        String encryptStr = AESUtils.getInstance().encrypt(JSONUtil.toJsonStr(jsonObject));
        long timeStamp = System.currentTimeMillis();
        String authSign = SignUtils.getEncryptSign(encryptStr, timeStamp);
        log.info("获取商户星级请求地址：{}, 请求参数：{}, 加密串：{}", mchStarUrl, encryptStr, authSign);
        try {

            HttpResponse response = HttpRequest.post(mchStarUrl)
                    .header("Content-Type", MediaType.TEXT_PLAIN_VALUE)
                    .header("sign-type", SignUtils.SIGN_TYPE)
                    .header("auth-apikey", SignUtils.API_KEY)
                    .header("auth-sign", authSign)
                    .header("auth-timestamp", String.valueOf(timeStamp))
                    .header("Referer","https://jrstyy.post183.net")
                    .timeout(20000)
                    .body(encryptStr)
                    .execute();
            log.info("respose:{}",JSONUtil.toJsonStr(response));
            String body = response.body();
            log.info("获取商户星级返回信息：{}",body);
            MchStarResponse mchStarResponse = JSONObject.parseObject(body, MchStarResponse.class);
            log.info("mchStarResponse:{}", JSONUtil.toJsonStr(mchStarResponse));
            String code = mchStarResponse.getCode();
            if ("0".equals(code)) {
                List<MchStar> data = mchStarResponse.getData();
                log.info("获取商户星级返回上一级信息:{}",JSONUtil.toJsonStr(data));
                return data;
            } else {
                throw new BizException(mchStarResponse.getMsg());
            }
        } catch (Exception e) { //出现异常，直接退出，避免死循环。
            log.error("error", e);
        }
        return null;
    }
}
